//
//  PayChannelViewController.swift
//  ddx0513
//
//  Created by ejian  on 15/6/9.
//  Copyright (c) 2015年 jiang yongbin. All rights reserved.
//

import UIKit

@objc protocol PopupDelegate {
    func dismissPopup(animated: Bool)
    optional func payResult(channel: String, resultStatus: String)
}


class PayChannelViewController: UITableViewController {
    var payChannelSelected = 0
    var weixinPay = 30.00
    var aliPay = 30.00
    var month = 0
    var paying = false
    var delegate: PopupDelegate?
    var hud: MBProgressHUD?

    @IBOutlet weak var moneyLabel: UILabel!
    @IBOutlet weak var weixinPayLabel: UILabel!
    @IBOutlet weak var aliPayLabel: UILabel!
    @IBOutlet weak var weixinPayCheckedImg: UIImageView!
    @IBOutlet weak var aliPayCheckedImg: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
        weixinPayLabel.text = "￥" + String(stringInterpolationSegment: weixinPay)
        aliPayLabel.text = "￥" + String(stringInterpolationSegment: aliPay)
        
        rowSelected(1)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func rowSelected(row: Int) ->Void {
        if (row == 1) {
            rowDeselected()
            payChannelSelected = 1
            weixinPayCheckedImg.hidden = false
            moneyLabel.text = weixinPayLabel.text! + "元"
        } else if (row == 2) {
            rowDeselected()
            payChannelSelected = 2
            aliPayCheckedImg.hidden = false
            moneyLabel.text = aliPayLabel.text! + "元"
        }
    }
    
    func rowDeselected() ->Void {
        if (payChannelSelected == 1) {
            weixinPayCheckedImg.hidden = true
        } else if (payChannelSelected == 2) {
            aliPayCheckedImg.hidden = true
        } 
    }
    
    func payOK() {
        if (payChannelSelected == 1 && !WXApi.isWXAppInstalled()) {
            ViewUtils.popMessage(self, title: "", message: "用户未安装微信客户端")
            self.delegate?.dismissPopup(false)
            return
        }
        
        startIndicator()
        let time: Int64 = Int64(NSDate().timeIntervalSince1970 * 1000)
        if (payChannelSelected == 1) {
            var a = ["userid": DBUtils.mem.userId, "token": DBUtils.mem.token, "month": month, "paychl": "SDK_WEIXIN", "timestamp": "\(time)", "device": "IPHONE"]
            NetUtils.netRequest(Method.POST, URLString: NetUtils.getURLBuyVip(), parameters: (a as! [String : AnyObject]), responseHandler: stopIndicator, netErrorHandler: netErrorHandler, successHandler: weixinPaySuccess, interErrorHandler: internalErrorHandler, jsonErrorHandler: jsonErrorHandler)
        } else if (payChannelSelected == 2) {
            var a = ["userid": DBUtils.mem.userId, "token": DBUtils.mem.token, "month": month, "paychl": "SDK_ALI", "timestamp": "\(time)", "device": "IPHONE"]
            NetUtils.netRequest(Method.POST, URLString: NetUtils.getURLBuyVip(), parameters: (a as! [String : AnyObject]), responseHandler: stopIndicator, netErrorHandler: netErrorHandler, successHandler: aliPaySuccess, interErrorHandler: internalErrorHandler, jsonErrorHandler: jsonErrorHandler)
        }
    }

    @IBAction func ExitButtonPressed(sender: AnyObject) {
        self.delegate?.dismissPopup(true)
    }
    
    //MARK: - 网络回调函数
    
    func startIndicator() {
        hud = MBProgressHUD(view: self.view)
        self.view.addSubview(hud!)
        hud?.labelText = "处理中.."
        hud?.show(true)
    }
    
    func stopIndicator() {
        hud?.hide(false)
    }
    
    func netErrorHandler() {
        paying = false
        MBHudUtils.showText("网络错误", view: view)
    }
    
    func internalErrorHandler(retCode: Int, retMsg: String) {
        paying = false
        MBHudUtils.showText(retMsg, view: self.view)
    }
    
    func jsonErrorHandler() {
        paying = false
        MBHudUtils.showText("系统错误", view: self.view)
    }
    
    func aliPaySuccess(json: JSON) {
        paying = false
        var orderNo = json["orderno"].string
        var tranStr = json["transtr"].string
        var price = json["price"].int
        var notifyUrl = json["notifyurl"].string
        
        if let str = tranStr {
            AlipaySDK.defaultService().payOrder(str, fromScheme: "alipay2088021052551456", callback: { (ret: [NSObject : AnyObject]!) -> Void in
                let ret1 = ret as! [String: String]
                self.delegate!.payResult!(StringUtils.payChannel["alipay"]!, resultStatus: ret1["resultStatus"]!)
                
            })
        }
    }
    
    func weixinPaySuccess(json: JSON) {
        paying = false
        var orderNo = json["orderno"].string
        var tranStr = json["transtr"].string
        var price = json["price"].int
        var notifyUrl = json["notifyurl"].string
        
        if let a = tranStr {
            let arr = StringUtils.splitTranStr(a)
            var request = PayReq()
            request.partnerId = arr["partnerid"]
            request.prepayId = arr["prepayid"]
            request.package = arr["package"]
            request.nonceStr = arr["noncestr"]
            request.timeStamp = UInt32(arr["timestamp"]!.toInt()!)
            request.sign = arr["sign"]
            WXApi.sendReq(request)
        }
    }
    
    
    // MARK: - Table view data source
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        switch (indexPath.row) {
        case 1, 2:
            rowSelected(indexPath.row)
            tableView.deselectRowAtIndexPath(indexPath, animated: true)
        case 3:
            tableView.deselectRowAtIndexPath(indexPath, animated: true)
            if (!paying) {
                paying = true
                payOK()
            }
        default:
            return
        }
    }

}
